#include <../inc/pwm.h>


/*control enable period duty*/
void write_pwm_file(int chip, int channel, const char *file, const char *value){
    char path[128];
    snprintf(path, sizeof(path),PWM_PATH "%s", chip, channel, file);
    //printf("%s\n", path);
    int fd=open(path,O_WRONLY);
    if(fd<0){
        perror("failed to open PWM_PATH\n");
        exit(1);
    }

    if(write(fd,value,strlen(value))<0){
        perror("failed to write pwm value\n");
        exit(1);
    }
    close(fd);
}


/*control export unexport*/
void write_pwm_file_port(int chip, int channel, const char *file, const char *value){
    char path[128];
    snprintf(path, sizeof(path),PWM_PATH_PORT "%s", chip,file);
    //printf("%s\n", path);
    int fd=open(path,O_WRONLY);
    if(fd<0){
        perror("failed to open PWM_PATH_PORT\n");
        exit(1);
    }

    if(write(fd,value,strlen(value))<0){
        perror("failed to write pwm value\n");
        exit(1);
    }
    close(fd);
}

void pwm_init(int pwm_chip,int pwm_channel){

    char path[100];
    snprintf(path, sizeof(path), PWM_PATH, pwm_chip,pwm_channel);
    printf("%s\n",path);
    FILE *fp=fopen(path,"w");
    if(fp){
        fprintf(fp,"%d", pwm_channel);
        fclose(fp);
    }
    printf("pwm initial ok\n");
    
}

void pwm_set_polarity(int pwm_chip,int pwm_channel,const char *polarity){
    char path[100];

    snprintf(path,sizeof(path), PWM_PATH_POLARITY,pwm_chip,pwm_channel);
    FILE *fp=fopen(path,"w");
    if(fp){
        fprintf(fp,"%s",polarity);      //normal or inversed
        fclose(fp);
    }
}

void pwm_set(int pwm_chip,int pwm_channel,int duty){
    char path[100];
    int period = 1000000;     //1kHz

    snprintf(path,sizeof(path), PWM_PATH_PERIOD,pwm_chip,pwm_channel);
    FILE *fp=fopen(path,"w");
    if(fp){
        fprintf(fp,"%d",period);
        fclose(fp);
    }

    snprintf(path,sizeof(path), PWM_PATH_DUTY_CYCLE,pwm_chip,pwm_channel);
    fp=fopen(path,"w");
    if(fp){
        fprintf(fp,"%d",duty);
        fclose(fp);
    }

    snprintf(path,sizeof(path), PWM_PATH_ENABLE,pwm_chip,pwm_channel);
    fp=fopen(path,"w");
    if(fp){
        fprintf(fp,"1");
        fclose(fp);
    }
}
void pwm_control(int period, int duty){

    char period_set[125];
    char duty_set[125];

    write_pwm_file_port(PWM_CHIP,PWM_CHANNEL,"export","0");
    usleep(100000);
    sprintf(period_set,"%d",period);
    printf("period set:%s\n",period_set);
    write_pwm_file(PWM_CHIP,PWM_CHANNEL,"period", period_set);

    sprintf(duty_set,"%d",duty);
    printf("duty set:%s\n",duty_set);
    write_pwm_file(PWM_CHIP,PWM_CHANNEL,"duty_cycle", duty_set);

    write_pwm_file(PWM_CHIP,PWM_CHANNEL,"enable", "1");
    printf("pwm set ok\n");
}

void pwm_disable(){

    write_pwm_file(PWM_CHIP,PWM_CHANNEL,"enable", "0");
    write_pwm_file_port(PWM_CHIP,PWM_CHANNEL,"unexport","0");
    printf("shutdown\n");

}